<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

use App\Http\Models\TemplateModel;
use App\Http\Models\PictureModel;

class TemplateController extends HomeController
{
    public function lists(Request $request)
	{
		try{

			$pagesize = $request->input('pagesize', 9);
			$pageno = $request->input('pageno', 1);
			$cate = $request->input('cate', 0);
			$search = $request->input('search', '');
			$sort = $request->input('sort', 0); // 0 默认 2 最新 1 最热

			$sqlRow = is_online() ? '`status` = 2 ' : ' `status` = 1 ';
			if($search !== '') {
				$sqlRow .= " AND (`title` LIKE '".$search."%' OR `desc` LIKE '".$search."%' ) ";
			}
			if ($cate > 4) {
				$sqlRow .= " AND find_in_set(".$cate.", `category`) ";
			}

			$orderKey = 'sort';
			switch ($sort) {
				case 2:
					$orderKey = 'id';
					break;
				case 1:
					$orderKey = 'used_times';
					break;
			}

			$data = TemplateModel::whereRaw($sqlRow)
				->orderBy($orderKey,"desc")
				->skip(($pageno-1) * $pagesize)
				->take($pagesize)
				->get();

			$pic_ids = array();
			$picid2templateid = array();
			$templateid2picurl = array();
			foreach ( $data as $key => $item ) {
				$pic_id = $item['icon_url'];
				$template_id = $item['id'];
				$pic_ids[] = $pic_id;
				$picid2templateid[$pic_id] = $template_id;
			}
			$pics = PictureModel::whereIn('id', $pic_ids)->get();
			foreach ($pics as $pic_item) {
				$pic_id = $pic_item['id'];
				$template_id = isset($picid2templateid[$pic_id]) ? $picid2templateid[$pic_id] : 0;
				$templateid2picurl[$template_id] = $pic_item['path'];
			}

			foreach ($data as $key => &$item) {
				$template_id = $item['id'];
				$item['icon_url'] = get_template_icon_url($templateid2picurl[$template_id]);
			}

			return response()->json(build_result(["info"=>build_template_info($data), "pagesize" => $pagesize, "pageno" => $pageno]));
		}catch(\Exception $e) {
			return response()->json(build_result('', '10001', $e->getMessage()));	
		}
	}
}


